package foo.bar.wiki.web.action.space;

import foo.bar.wiki.web.action.BaseActionBean;
import foo.bar.wiki.web.extension.SpaceTypeConverter;
import foo.bar.wiki.services.WikiService;
import foo.bar.wiki.services.exception.BusinessLogicExecution;
import foo.bar.wiki.domain.Space;
import foo.bar.wiki.utils.WikiUtils;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.*;

/**
 * @author tmjee
 * @version $Date$ $Id$
 */
public class AddSpaceActionBean extends BaseActionBean {

    public static final String VIEW = "/space/addSpace.jsp";

    private WikiService wikiService;

    @Validate(converter = SpaceTypeConverter.class, on={"save"})
    @ValidateNestedProperties({
        @Validate(field="name", trim = true, required = true, on={"save"}),
        @Validate(field="description", trim=true, required=true, on={"save"}),
        @Validate(field="themeName", trim=true, required=true, on={"save"})
    })
    private Space space;


    @DefaultHandler
    public Resolution view() {
        space = new Space();
        return new ForwardResolution(generateThemePath(VIEW));
    }


    public Resolution save() throws Throwable {
        return (Resolution) handleBusinessLogicException(new BusinessLogicExecution(){
            public Resolution execute() throws Throwable {
                space = wikiService.saveSpace(space);
                getContext().getMessages().add(new SimpleMessage("Space ["+space.getName()+"] saved successfully"));
                return new RedirectResolution(EditSpaceActionBean.class, "view").addParameter("space", space.getId());
            }
        });
    }
    @ValidationMethod(on={"save"})
    public void validate_save(ValidationErrors validationErrors) {
        if (!WikiUtils.isValidWikiPageOrSpaceName(space.getName())) {
            validationErrors.add("space.name", new SimpleError("Space name should be alphanumeric ( '_' character is allowed) "));
        }
    }


    @SpringBean("wikiService")
    public void setWikiService(WikiService wikiService) {
        this.wikiService = wikiService;
    }


    public Space getSpace() {
        return space;
    }

    public void setSpace(Space space) {
        this.space = space;
    }
}
